#pragma once
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>
#include<unistd.h>
using namespace std;

const char *pathname = "/home/gm";
const char proj_id = 0x66;

const int defaultsize = 4096; // 单位是字节

string ToHex(key_t key)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", key);
    return buffer;
}

key_t GetShmKeyorDie()
{
    key_t k = ftok(pathname, proj_id);
    if (k < 0)
    {
        cerr << "ftok error, errno: " << errno << ", error string: " << strerror(errno) << endl;
        exit(1);
    }

    return k;
}

int CreatShmorDie(key_t key, int size, int flag)
{
    int shmid = shmget(key, size, flag);
    if (shmid < 0)
    {
        cerr << "ftok error, errno: " << errno << ", error string: " << strerror(errno) << endl;
        exit(2);
    }

    return shmid;
}

int CreatShm(key_t key, int size)
{
    // IPC_CREAT: 不存在就创建，存在就获取
    // IPC_EXCL: 没有意义
    // IPC_CREAT | IPC_EXCL: 不存在就创建，存在就出错返回
    return CreatShmorDie(key, size, IPC_CREAT | IPC_EXCL);
}

int GetShm(key_t key, int size)
{
    return CreatShmorDie(key, size, IPC_CREAT);
}

void DeleteShm(int shmid)
{
    struct shmid_ds shmds;
    int n = shmctl(shmid, IPC_RMID, nullptr);
    if (n < 0)
    {
        cerr << "DeleteShm error, errno: " << errno << ", error string: " << strerror(errno) << endl;
    }
    else
    {
        cout << "Shmctl DeleteShm success shmid:" << shmid << endl;
    }
}

void ShmDebug(int shmid)
{
    struct shmid_ds shmds;
    int n = shmctl(shmid, IPC_STAT, &shmds);
    if (n < 0)
    {
        cerr << "ShmDebug error, errno: " << errno << ", error string: " << strerror(errno) << endl;
        return;
    }
    cout<<"shmds.shm_segsz:"<<shmds.shm_segsz<<endl;
    cout<<"shmds.shm_ctime:"<<shmds.shm_ctime<<endl;
    cout<<"shmds.shm_nattch:"<<shmds.shm_nattch<<endl;
    cout<<"shmds.shm_perm.__key:"<<ToHex(shmds.shm_perm.__key)<<endl;

}


void* ShmAttach(int shmid)
{
    void* addr = shmat(shmid,nullptr,0);
    if((long long int)addr == -1 )
    {
        cerr << "ShmAttach error, errno: " << errno << ", error string: " << strerror(errno) << endl;
        return nullptr;
    }
    return addr;
}


void ShmDetach(char* addr)
{
    int n = shmdt(addr);
    if(n<0)
    {
        cerr << "ShmDetach error, errno: " << errno << ", error string: " << strerror(errno) << endl;
    }
}